﻿Module ScreenObjectExtensions
    <System.Runtime.CompilerServices.Extension()>
    Public Function FindControls(screen As Microsoft.LightSwitch.Client.IScreenObject) As IEnumerable(Of IContentItemProxy)
        Dim model = screen.Details.GetModel()
        ' recursion, but screens are not that complex
        Return model.GetChildItems().SelectManyRecursive(Function(c) c.GetChildItems()).OfType(Of Microsoft.LightSwitch.Model.IContentItemDefinition)().[Select](Function(c) screen.FindControl(c.Name))
    End Function

    <System.Runtime.CompilerServices.Extension()>
    Public Iterator Function SelectManyRecursive(Of T)(source As IEnumerable(Of T), selector As Func(Of T, IEnumerable(Of T))) As IEnumerable(Of T)
        For Each item As T In source
            Yield item

            Dim children = selector(item)
            If children Is Nothing Then
                Continue For
            End If
            For Each descendant As T In children.SelectManyRecursive(selector)
                Yield descendant
            Next
        Next
    End Function
End Module
